package com.yjt.common.exceptions;

import com.yjt.common.enums.ResultCodeEnum;
import com.yjt.common.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @program:
 * @description: 异常处理
 * @author: zengzhiping
 * @create: 2020-07-03 14:18
 **/
@ControllerAdvice
@Slf4j
public class ExceptionHandlers {

    /**
     * 处理运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public CommonResult runTimeHandle(RuntimeException e) {
        e.printStackTrace();
        log.error("错误信息为：{}",e.getMessage());
        return CommonResult.error(ResultCodeEnum.Error.getCode(), ResultCodeEnum.Error.getMsg());
    }


    /**
     * 统一异常处理，表单验证处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResult notValidHandle(MethodArgumentNotValidException e) {
        log.error("错误信息为：{}",e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        return CommonResult.error(ResultCodeEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
    }

    /**
     * 锁异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RedisLockException.class)
    @ResponseBody
    public CommonResult redisLockException(RedisLockException e) {
        log.error("错误信息为：{}",e.getMessage());
        return CommonResult.success(e.getMessage());
    }

}
